/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.bomt.controller;

import com.alibaba.excel.EasyExcel;
import com.comac.ins.bomt.common.enums.BizStepEnum;
import com.comac.ins.bomt.domain.vo.BomtTreeNodeVo;
import com.comac.ins.bomt.domain.vo.KeywordItemListVo;
import com.comac.ins.bomt.domain.vo.KeywordVo;
import com.comac.ins.bomt.service.KeywordListService;
import com.comac.ins.common.core.domain.R;
import com.comac.ins.common.biz.utils.BizAssertUtil;
import com.comac.ins.common.biz.annotations.Digest;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.satoken.utils.LoginHelper;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


/**
 * 关键词列表控制器
 *
 * @author zhanghongyi
 * @date 2024/8/1 14:33
 * @description BomController
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/keyword-list")
public class KeywordListController {

    private final KeywordListService keywordListService;

    /**
     * 创建关键词列表
     *
     * @param aircraftModel 机型
     * @param listCode      列表编码
     * @param listName      列表名称
     * @param bindStep      绑定步骤，OBOM_SBOM_CONVERT-原始装机清单向标准装机清单转换，SBOM_QBOM_CONVERT-标准装机清单向强度数模清单转换
     * @param file          初始化excel文件(可选)
     * @return 结果
     */
    @PostMapping(value = "/create/{aircraftModel}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Digest(bizType = "biz-keyword-list-create", logFields = {"aircraftModel", "listCode", "bindStep", "file?.getOriginalFilename()"})
    public R<Void> create(
        @NotBlank(message = "机型不能为空") @PathVariable String aircraftModel,
        @RequestPart(value = "listCode", required = false) String listCode,
        @NotBlank(message = "列表名称不能为空") @RequestPart("listName") String listName,
        @NotBlank(message = "绑定步骤不能为空") @RequestPart("bindStep") String bindStep,
        @RequestPart(value = "file", required = false) MultipartFile file
    ) throws IOException {
        if(StringUtils.isBlank(listCode)){
            listCode = aircraftModel + DigestUtils.md5Hex(listName);
        }
        BizAssertUtil.notNull(BizStepEnum.getByType(bindStep), "bindStep not recognized");
        List<String> keywordList = new ArrayList<>();
        if (null != file && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                BizAssertUtil.isTrue(fileName.endsWith(".xlsx"), "please use xlsx to init");
            }
            List<KeywordItemListVo> keywordItemListVos = EasyExcel.read(file.getInputStream()).head(KeywordItemListVo.class).autoCloseStream(false).sheet().doReadSync();
            keywordList = keywordItemListVos.stream().map(KeywordItemListVo::getKeyword).toList();
        }

        keywordListService.create(LoginHelper.getLoginUser(), listCode, listName, BizStepEnum.getByType(bindStep), aircraftModel, keywordList);
        return R.ok("success");
    }

    /**
     * 删除关键词列表
     *
     * @param aircraftModel 机型
     * @param listCode      列表编码
     * @return 结果
     */
    @PostMapping(value = "/drop/{aircraftModel}/{listCode}")
    @Digest(bizType = "biz-keyword-list-drop", logFields = {"aircraftModel", "listCode"})
    public R<Void> drop(@NotBlank(message = "机型不能为空") @PathVariable String aircraftModel,
                        @NotBlank(message = "列表编码不能为空") @PathVariable String listCode) {
        keywordListService.drop(LoginHelper.getLoginUser(), listCode, aircraftModel);
        return R.ok("success");
    }


    /**
     * 删除关键词
     *
     * @param aircraftModel 机型
     * @param listCode      列表编码
     * @param keywords      关键词
     */
    @DeleteMapping("/delete/{aircraftModel}/{listCode}")
    @Digest(bizType = "biz-keyword-list-delete", logFields = {"aircraftModel", "listCode", "T(org.apache.commons.lang3.StringUtils).join(keywords,',')"})
    public R<Void> delete(@NotBlank(message = "机型不能为空") @PathVariable String aircraftModel,
                          @NotBlank(message = "列表编码不能为空") @PathVariable String listCode,
                          @NotNull(message = "关键词不能为空") @RequestBody List<String> keywords) {
        keywordListService.delete(LoginHelper.getLoginUser(), listCode, aircraftModel, new HashSet<>(keywords));
        return R.ok("success");
    }

    /**
     * 新增关键词
     *
     * @param aircraftModel 机型
     * @param listCode      列表代码
     * @param keywords      关键词列表
     */
    @PutMapping("/add/{aircraftModel}/{listCode}")
    @Digest(bizType = "biz-keyword-list-add", logFields = {"aircraftModel", "listCode", "T(org.apache.commons.lang3.StringUtils).join(keywords,',')"})
    public R<Void> add(@NotBlank(message = "机型不能为空") @PathVariable String aircraftModel,
                       @NotBlank(message = "列表编码不能为空") @PathVariable String listCode,
                       @NotNull(message = "关键词不能为空") @RequestBody List<String> keywords) {
        keywordListService.add(LoginHelper.getLoginUser(), listCode, aircraftModel, new HashSet<>(keywords));
        return R.ok("success");
    }

    /**
     * 查询关键词
     *
     * @param aircraftModel 机型
     * @param listCode      列表代码
     * @param keyword       关键词（可选）
     * @return 关键词列表
     */
    @GetMapping("/query/{aircraftModel}/{listCode}")
    public TableDataInfo<KeywordVo> query(@NotBlank(message = "机型不能为空") @PathVariable String aircraftModel,
                                          @NotBlank(message = "列表编码不能为空") @PathVariable String listCode,
                                          @RequestParam(required = false) String keyword,
                                          PageQuery pageQuery

    ) {
        return keywordListService.queryByPage(LoginHelper.getLoginUser(), listCode, aircraftModel, keyword, pageQuery);
    }

    /**
     * 查询所有列表
     *
     * @return 关键词列表树
     */
    @GetMapping("/query-list/all")
    public R<List<BomtTreeNodeVo>> queryAllList() {
        List<BomtTreeNodeVo> result = keywordListService.queryAll(LoginHelper.getLoginUser());
        return R.ok(result);
    }
}
